package com.example.books.Config;

import com.example.books.Dao.UserDao;
import com.example.books.Pojo.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class Userdetails implements UserDetailsService {


    @Autowired
    private  BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private  UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserDO userDO = userDao.login(s);
        if(userDO!=null){
            return new User(userDO.getUsername(),bCryptPasswordEncoder.encode(userDO.getPassword()), Arrays.asList(new SimpleGrantedAuthority("admin")));
        }else {
            throw new UsernameNotFoundException("用户不存在！");
        }

    }
}
